﻿@using System.Web.Script.Serialization
@{
    ViewBag.Title = T("Admin.Product.Edit.Title");
     Layout = "~/views/shared/_AdminLayout.cshtml";
}

<h5>@T("Admin.Product.Edit.Title") <span data-bind="text:ProductName"></span></h5>

@Html.Partial("ManageProductMenu")


<div class="tab-content">
    <div class="tab-pane active" id="pInfo">
        @Html.Partial("_ProductInfo_Edit")
    </div>
    <div class="tab-pane" id="pv">
        @Html.Partial("_ProductVariant_List")
    </div>
    <div class="tab-pane" id="pp">
        @Html.Partial("_ProductPicture_List")
    </div>
    <div class="tab-pane" id="psa">
        @Html.Partial("_ProductSpecificationAttribute_List")
    </div>
</div>





@{
    var model = ViewBag.Model;
    var jsonStr = new HtmlString(new JavaScriptSerializer().Serialize(model));
}


    @Styles.Render("~/content/fineuploader/fineuploader-3.5.0.css")
    @Scripts.Render("~/content/fineuploader/fineuploader-3.5.0.js")
    @Scripts.Render("~/content/fineuploader/iframe.xss.response-3.5.0.js")


@section scripts
{
    
    @Scripts.Render("~/content/editor/tinymce/tinymce.js")

    <script>
        $(function() {
            $('#myTab a[href="#@ViewBag.Tab"]').tab('show');
        })
    </script>

    <script>
        var init = @jsonStr;


        function ProductSpecificationAttribute(specificationAttributeName, optionName) {

            var self = this;
            self.SpecificationAttributeName = ko.observable(specificationAttributeName);
            self.OptionName = ko.observable(optionName);
        }

        function ProductPictureModel(id, pictureId, pictureUrl, displayOrder) {
            this.Id = ko.observable(id);
            this.PictureId = ko.observable(pictureId);
            this.DisplayOrder = ko.observable(displayOrder);
            this.PictureUrl = ko.observable(pictureUrl);

        }

        function NewProductPictureModel(productId, pictureUrl) {
            var self = this;
            self.ProductId = ko.observable(productId);
            self.PictureId = ko.observable(0).extend({
                notEqual: { message: '@T("Admin.ProductPicture.NeedPicture")', params: 0 }
            });
            self.PictureUrl = ko.observable(pictureUrl);
            self.DisplayOrder = ko.observable(0).extend({
                required: { message: '@T("Admin.ProductPicture.NeedDisplayOrder")' },
                digit: { message: '@T("Admin.ProductPicture.DisplayOrderFormatError")' }
            });
            self.errors = ko.validation.group(self);
        }

        function ProductVariantModel(id, name, sku, price, stockQuantity, displayOrder, published) {

            this.Id = ko.observable(id);
            this.Name = ko.observable(name);
            this.Sku = ko.observable(sku);
            this.Price = ko.observable(price);
            this.StockQuantity = ko.observable(stockQuantity);
            this.DisplayOrder = ko.observable(displayOrder);
            this.Published = ko.observable(published);
        }

        function ProductModel() {
            var self = this;
            self.Id = ko.observable(init.Id);


            self.Picture = new NewProductPictureModel(init.Id, init.DefaultUploadPicture.PictureUrl);

            self.ProductName = ko.observable(init.ProductName).extend({
                required: { message: '@T("Admin.Product.NeedProductName")' },
                maxLength: 400
            });

            self.ShortDescription = ko.observable(init.ShortDescription).extend({
                required: { message: '@T("Admin.Product.NeedShortDescription")' },
            });
            self.FullDescription = ko.observable(init.FullDescription).extend({
                required: { message: '@T("Admin.Product.NeedFullDescription")' },
            });
            self.IsPublished = ko.observable(init.IsPublished);

            var tempProductPictures = $.isEmptyObject(init.ProductPictures) ? [] : $.map(init.ProductPictures, function(a) {
                return new ProductPictureModel(a.ProductPictureId, a.PictureId, a.PictureUrl, a.DisplayOrder);
            });

            var tempProductVariants = $.isEmptyObject(init.ProductVariants) ? [] : $.map(init.ProductVariants, function(a) {
                return new ProductVariantModel(a.Id, a.Name, a.Sku, a.Price, a.StockQuantity, a.DisplayOrder, a.Published);
            });

            var tempProductSpecificationAttributes = $.isEmptyObject(init.ProductSpecificationAttributes) ? [] : $.map(init.ProductSpecificationAttributes, function(a) {
                return new ProductSpecificationAttribute(a.SpecificationAttributeName, a.SpecificationAttributeOptionName);
            });


            self.ProductVariants = ko.observableArray(tempProductVariants);
            self.ProductPictures = ko.observableArray(tempProductPictures);
            self.ProductSpecificationAttributes = ko.observableArray(tempProductSpecificationAttributes);


            self.DeleteProductPicture = function(p) {
                if (confirm('@T("admin.productpicture.delete.confirm")')) {
                    var data = {
                        ProductPictureId: p.Id()
                    };
                    
                    $.ajax({
                        url: "/api/ProductPictureApi/DeleteProductPicture",
                        type: 'post',
                        data: ko.toJSON(data),
                        contentType: 'application/json',
                        success: function(result) {

                            if (result.Status == "0") {
                                self.ProductPictures.remove(p);
                                toastr.success(result.Message);
                                //alert("保存成功");
                            } else {
                                toastr.errror(result.Message);
                                //alert("保存失败：" + result.Msg);
                            }
                        }
                    });
                }
            };
            self.DeleteProductVariant = function(p) {

                if (confirm('@T("admin.productvariant.delete.confirm")')) {
                    var data = {
                        ProductVariantId: p.Id()
                    };
                    $.ajax({
                        url: "/api/ProductVariantApi/DeleteProductVariant",
                        type: 'post',
                        data: ko.toJSON(data),
                        contentType: 'application/json',
                        success: function(result) {

                            if (result.Status == "0") {
                                self.ProductVariants.remove(p);
                                toastr.success(result.Message);
                            } else {
                                toastr.error(result.Message);
                            }
                        }
                    });
                }
            };

            self.SaveProductInfo = function() {

                self.FullDescription(tinyMCE.activeEditor.getContent());
                if (this.isValid()) {
                    $.ajax({
                        url: "/api/ProductApi/UpdateProductInfo",
                        type: 'post',
                        data: ko.toJSON(self),
                        contentType: 'application/json',
                        success: function(result) {

                            if (result.Status == "0") {
                                toastr.success(result.Message);
                            } else {
                                toastr.error(result.Message);
                            }
                        }
                    });
                } else {
                    self.errors.showAllMessages();
                }
            };


            self.AddProductPicture = function() {

                if (self.Picture.errors().length === 0) {
                    $.ajax({
                        url: "/api/ProductPictureApi/InsertProductPicture",
                        type: 'post',
                        data: ko.toJSON(self.Picture),
                        contentType: 'application/json',
                        success: function(result) {

                            if (result.Status == "0") {
                                self.ProductPictures.push(new ProductPictureModel(result.Id, self.Picture.PictureId(),self.Picture.PictureUrl(), self.Picture.DisplayOrder()));
                                //toastr.success(result.Message);
                            } else {
                                alert("保存失败：" + result.Msg);
                            }
                        }
                    });
                } else {
                    self.Picture.errors.showAllMessages();
                }

            };

        }

        var vm = new ProductModel();
        vm.errors = ko.validation.group(vm);
        ko.applyBindings(vm);

    </script>
    
    <script type="text/javascript">

         //Notes: autosave plugin is disabled
        (function() {

            tinyMCE.init({
                width: 544,
                selector: "#FullDescription",

                verify_html: false,
                plugins: [
                    "advlist autolink lists link image charmap print preview anchor",
                    "searchreplace visualblocks code fullscreen",
                    "insertdatetime media table contextmenu paste jbimages"
                ],
                toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image jbimages",
            });

        })();

        $(document).ready(function() {

            var errorHandler = function(event, id, fileName, reason) {
                qq.log("id: " + id + ", fileName: " + fileName + ", reason: " + reason);
            };


            var uploader2 = new qq.FineUploader({
                element: $('#manualUploadModeExample')[0],
                autoUpload: true,
                uploadButtonText: "Select Files",
                request: {
                    endpoint: "/FineUploader/UploadFile",
                    params: { "extraParam1": "true", "picSize": "100" }
                },
                callbacks: {
                    onError: errorHandler,
                    onComplete: function(id, fileName, responseJSON) {
                        if (responseJSON.success) {
                            vm.Picture.PictureId(responseJSON.OriginalPictureId);
                            vm.Picture.PictureUrl(responseJSON.NewPictureUrl);
                        }
                    }
                }
            });
        });
    </script>


}
